// -*- mode:javascript; indent-tabs-mode: nil -*-

// chad.talbott@gmail.com
// everything I know, I learned from
// http://ninja.frozenfractal.com/main.js and Google
// I should probably use jquery, too

window.requestAnimFrame = (function(callback) {
    return window.requestAnimationFrame
        || window.webkitRequestAnimationFrame
        || window.mozRequestAnimationFrame
        || window.oRequestAnimationFrame
        || window.msRequestAnimationFrame
        || function(callback) {
            window.setTimeout(callback, 1000 / 60);
        };
})();

var canvas;
var context;
var pause_button;

var paused = 0;

var x = 0;
var y = 0;
var sy = 1;
var sx = 1;
var rw = 50;
var rh = 50;

function animate() {
    // update
    if (x < 0 || x + rw > canvas.width) {
	console.log("bounce");
        sx = -sx;
    }
    if (y < 0 || y + rh > canvas.height) {
        console.log("bounce");
        sy = -sy;
    }
    x += sx;
    y += sy;

    // clear
    context.clearRect(0, 0, canvas.width, canvas.height);

    // draw stuff
    context.fillStyle="#FF0000";
    context.fillRect(x,y,rw,rh);

    // request new frame
    if (!paused) {
        requestAnimFrame(function() {
            animate();
        });
    }
}

function onkeydown(e) {
    console.log('pressed: ' + e.keyCode.toString());

    // if we're paused, can only unpause, other keys are essentially
    // unbound.
    if (paused) {
        if (e.keyCode == 32) {
            pause();
            e.preventDefault();
            return false;
        }
        return true;
    }

    switch (e.keyCode) {
    case 37: case 65: case 79: sx = -1; sy = 0; break; // left
    case 39: case 68: case 85: sx = 1;  sy = 0; break; // right
    case 38: case 87: case 190: sy = -1; sx = 0; break; // up
    case 40: case 83: case 69: sy = 1;   sx = 0; break; // down
    case 32: pause(); break;                            // space
    default: return true;
    }
    e.preventDefault();
    return false;
}

function onkeyup(e) {
    switch (e.keyCode) {
    case 37: case 65: case 79: sx = 0; break;  // left
    case 39: case 68: case 85: sx = 0; break;  // right
    case 38: case 87: case 190: sy = 0; break; // up
    case 40: case 83: case 69: sy = 0; break;  // down
    default: return true;
    }
    e.preventDefault();
    return false;
}

function pause() {
    paused = !paused;
    if (!paused) {
        requestAnimFrame(animate);
        pause_button.innerHTML = "Pause";
    } else {
        pause_button.innerHTML = "Play";
    }
}

function main() {
    body = document.getElementById('body');
    canvas = document.getElementById('canvas');
    context = canvas.getContext('2d');
    pause_button = document.getElementById("pause");

    body.onkeydown = onkeydown;
    // body.onkeyup = onkeyup;

    animate();
}
